<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model\DepartmentModel;

class Tablesend extends Base{
	/**
	 * [首页]
	 */
	public function index() {
		$DepartModel = new DepartmentModel();
		$departs_opt = $DepartModel->getCanSeeDepart(session('id'));
		$departs_opt = $this->arr2tree($departs_opt);
		$departs_opt = $this->getNameByTree($departs_opt);
		$department = DB::name('department')->alias('depart')
					->join('role role','depart.id = role.department_id')
					->join('user user','user.role_id = role.id')
					->where('user.id',session('id'))
					->field('depart.name,depart.id')->find();
		$this->assign([
			'departs_opt' => $departs_opt,
			'department' => $department
		]);
		return $this->fetch();
	}

	/**
	 * [查询各种报表的报送情况]
	 */
	public function getSendResult() {
		$param = input("post.");
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$where = [
			'rpt_date' => ['between',[$param['s_time'],$param['e_time']]],
			'depart_id' => $param['depart_id']
		];
		switch ($param['type']) {
			case '1':
				# 日报
				$tableName = "table_day";
				$timeFormat = "Y年m月d日";
				$table_type = "日报";
				break;
			case '2':
				# 月报
				$tableName="table_month";
				$timeFormat="Y年m月";
				$table_type = "月报";
				break;
			case '3':
				# 年报
				$tableName="table_year";
				$timeFormat="Y年";
				$table_type = "年报";
				break;
			case '4':
				# 固定资产
				$tableName="table_asset";
				$timeFormat="Y年m月";
				$table_type = "固定资产";
				break;
			default :
				return ['code'=>0,'msg'=>'报表类型选择错误','data'=>''];
				break;
		}
		$can_see = session('can_see');
		$return['rows'] = DB::name($tableName)
			->where(function($query)use($can_see){
	            foreach($can_see as $k => $v){
	                if(is_array($v)){
	                    $query->whereOr(array_keys($v)[0],array_values($v)[0]);
	                }else{
	                    $query->whereOr($v);
	                }
	            }
	        })->where($where)->limit($offset,$limit)
			->order('rpt_date asc')->select();
		$return['total'] = DB::name($tableName)->where($where)->count();
		foreach($return['rows'] as &$v){
			$v['rpt_date'] = date($timeFormat,$v['rpt_date']);
			$v['table_type'] = $table_type;
			if($v['is_commit'] == 1){
				$v['is_commit_name'] = "已提交";
			}else{
				$v['is_commit_name'] = "未提交";
			}
			$v['depart_name'] = DB::name('department')->where("id",$v['depart_id'])->value('name');
		}
		if($return['total'] != 0){
			return ['code'=>1,'msg'=>'表格加载成功','data'=>$return];
		}else{
			return ['code'=>-1,'msg'=>'没有找到匹配结果','data'=>''];
		}
	}
}
